﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DAL
{
    public class BookDAL
    {
        //private static MyDBEntities db;

        static BookDAL()
        {
          //  db = new MyDBEntities();
        }

        public static List<Book> selectAll()
        {
            using (var db = new MyDBEntities())
            {
                return db.Book.ToList();
            }
            
        }
        public static MyResult Add(Book bk)
        {
            using (var db = new MyDBEntities())
            {
                db.Book.Add(bk);
                db.SaveChanges();
                return new MyResult(200, "添加OK", null);
            }
        }

        public static MyResult Delete(int id)
        {
            using (var db = new MyDBEntities())
            {
                var bk = db.Book.FirstOrDefault(b => b.f_id == id);
                db.Book.Remove(bk);
                db.SaveChanges();
                return new MyResult(200, "删除OK", bk);
            }
        }
        public static MyResult BatchDelete(string ids) // "2,3,4,5".split(',') ===> [ ]
        {
            using (var db = new MyDBEntities())
            {

                string[] arr = ids.Split(',');
                int iId = 0;
                foreach (var id in arr)
                {
                    iId = Convert.ToInt32(id);
                    var book = db.Book.FirstOrDefault(bk => bk.f_id == iId);
                    db.Book.Remove(book);

                }
                db.SaveChanges();
                return new MyResult(200, "批量删除OK", null);
            }
        }

        public static MyResult Edit( int id)
        {
            using (var db = new MyDBEntities())
            {
                var book = db.Book.FirstOrDefault(bk => bk.f_id == id);
                MyResult result = new MyResult(200, "", book);
                return result;
            }
        }

        public static MyResult Update(Book book)
        {
            using (var db = new MyDBEntities())
            {
                var old = db.Book.FirstOrDefault(bk => bk.f_id == book.f_id);
                old.f_author = book.f_author;
                old.f_image = book.f_image;
                old.f_price = book.f_price;
                old.f_title = book.f_title;
                old.f_type = book.f_type;
                db.SaveChanges();
                MyResult result = new MyResult(200, "修改完毕....", null);
                return result;
            }
        }
    }
}
